﻿resumeApp.factory('personalInfoService', ['$http', '$log', '$q', function($http, $log, $q) {
    var pInfos = [];
    var isInit = false;
    var isReady = function() {
        return isInit;
    };

    var getPersonalInfos = function () {
        var deferred = $q.defer();
        
        $http({
            method: 'GET',
            url: '/api/PersonalInfo'
        }).success(function(data, status, headers, config) {
            $log.info(data, status, headers(), config);
            angular.copy(data, pInfos);
            isInit = true;
            deferred.resolve();
        }).error(function(data, status, headers, config) {
            $log.warn(data, status, headers(), config);
            deferred.reject(status);
        });
        return deferred.promise;
    };

    var addPersonalInfo = function (personalInfo) {
        var deferred = $q.defer();
        
        $http({
            method: 'PUT',
            url: '/api/PersonalInfo/Insert',
            data: personalInfo
        }).success(function(data, status, headers, config) {
            $log.info(data, status, headers(), config);
            pInfos.push(data);
            deferred.resolve(data);
        }).error(function (data, status, headers, config) {
            $log.warn(data, status, headers(), config);
            deferred.reject(status);
        });
        return deferred.promise;
    };
    
    var getPersonalInfo = function (id) {
        var deferred = $q.defer();
        $http({
            method: 'GET',
            url: '/api/PersonalInfo/' + id
        }).success(function (data, status, headers, config) {
            $log.info(data, status, headers(), config);
            deferred.resolve(data);
        }).error(function (data, status, headers, config) {
            $log.warn(data, status, headers(), config);
            deferred.reject(status);
        });
        return deferred.promise;
    };
    
    var updatePersonalInfo = function(personalInfo) {
        var deferred = $q.defer();
        $http({
            method: 'POST',
            url: '/api/PersonalInfo/Update',
            data: personalInfo
        }).success(function (data, status, headers, config) {
            $log.info(data, status, headers(), config);
            deferred.resolve(data);
        }).error(function (data, status, headers, config) {
            $log.warn(data, status, headers(), config);
            deferred.reject(status);
        });
        return deferred.promise;
    };
    
    return {
        personalInfos: pInfos,
        isReady: isReady,
        getPersonalInfos: getPersonalInfos,
        addPersonalInfo: addPersonalInfo,
        getPersonalInfo: getPersonalInfo,
        updatePersonalInfo: updatePersonalInfo
    };
}]);